//
//  RequestTaxiView.m
//  easyTaxi
//
//  Created by ellenpage on 12-12-10.
//  Copyright (c) 2012年 ellenpage. All rights reserved.
//

#import "Constant.h"
#import "SocketObject.h"
#import "PassValueClass.h"
#import "RequestCMD.h"
#import "RequestTaxiView.h"
#import "TTSWidget.h"
#import "BMapKit.h"
#import "Constant.h"
#import "PassValueClass.h"
#import "MBProgressHUD.h"
#import "ZhiFuView.h"

#define kRecongnizerRect CGRectMake(23,63,282,210)

bool isAddThisAddress;

@interface RequestTaxiView ()<UITextFieldDelegate,BMKSearchDelegate,UIAlertViewDelegate,UITableViewDataSource,UITableViewDelegate,TTSWidgetDelegate>

@property (weak, nonatomic) IBOutlet UIButton *addThisAddressBtn;

@property (weak, nonatomic) IBOutlet UITextField *startPlace;

@property (weak, nonatomic) IBOutlet UITextField *endPlace;

@property (weak, nonatomic) IBOutlet UIScrollView *backGroundSRView;

@property (retain, nonatomic) ConfirmAddressView *addressResultView;

@property (retain, nonatomic) TTSWidget *ttsWidget;

@property (retain, nonatomic) BMKSearch      *POISearcher; //搜索poi信息
@property (retain, nonatomic) BMKPoiResult   *resultpoi;   //搜索结果

@property (weak, nonatomic) IBOutlet UIButton *requestBtn;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;

@property (weak, nonatomic) IBOutlet UIView *addressListView;
@property (weak, nonatomic) IBOutlet UITableView *addressTBView;

@property (retain, nonatomic) NSMutableArray *dataArray;

@property (weak, nonatomic) IBOutlet UILabel *daCheDouLbl;
@property (weak, nonatomic) IBOutlet UILabel *costDaCheDouLbl;

@property (weak, nonatomic) IBOutlet UIButton *addCoinsBtn;
@property (weak, nonatomic) IBOutlet UIButton *minusCoinsBtn;


- (IBAction)hideddressView;
- (IBAction)resignKeyboard;
- (IBAction)openAddressView;
- (IBAction)addThisAddress;
- (IBAction)cancelThisView;
- (IBAction)requestTaxi;//开始打车,进入poi结果界面

- (IBAction)openBuyCoinsView;
- (IBAction)addCoins;
- (IBAction)minusCoins;

@end

@implementation RequestTaxiView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self = [[[NSBundle mainBundle] loadNibNamed:@"RequestTaxiView" owner:self options:nil] objectAtIndex:0];
        [self loadData];
        [self initialData];//初始化数据
    }
    return self;
}

#pragma mark - Goback - 返回

- (IBAction)cancelThisView
{
    self.hidden = YES;
}

#pragma mark - InitialData - 初始化数据

- (void)loadData
{
    _dataArray = [NSMutableArray array];
    
    CGRect btn1Rect = CGRectMake(20,  iP5 ? 409 : 325, 130, 40);
    
    CGRect btn2Rect = CGRectMake(175, iP5 ? 409 : 325, 130, 40);

    _startPlace.text = [PassValueClass sharedIntance].startAddress;
    _startPlace.userInteractionEnabled = NO;
    _endPlace.delegate = self;
    _endPlace.text     = nil;
    
    _POISearcher = [[BMKSearch alloc] init];
    _POISearcher.delegate = self;
    
    _addressResultView = [[ConfirmAddressView alloc] init];
    [self addSubview:_addressResultView];
    _addressResultView.backgroundColor = [[UIColor darkTextColor] colorWithAlphaComponent:0.6];
    _addressResultView.hidden = YES;
    
    _requestBtn.frame = btn1Rect;
    _cancelBtn.frame  = btn2Rect;
    
    [self addSubview:_addressListView];
    _addressListView.hidden = YES;

    _addressTBView.delegate   = self;
    _addressTBView.dataSource = self;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(getDaCheDou)
                                                 name:kGetDaCheDouNoti
                                               object:nil];//获得打车豆通知
    [PassValueClass sharedIntance].costDaCheDou = @"0";
    [PassValueClass sharedIntance].typeStr      = @"0";
}

- (void)setDelegate:(id)delegate
{
    [self.addressResultView setDelegate:delegate];
}

- (void)initialData
{
    _startPlace.text  = [PassValueClass sharedIntance].startAddress;
    _endPlace.text    =  nil;
    
    _daCheDouLbl.text = [PassValueClass sharedIntance].daCheDouStr;
    _costDaCheDouLbl.text = @"0";
}

#pragma mark - NSNotification - 更新打车豆通知

- (void)getDaCheDou
{
    _daCheDouLbl.text     = [PassValueClass sharedIntance].daCheDouStr;
    _costDaCheDouLbl.text = @"0";
    
    [PassValueClass sharedIntance].costDaCheDou = @"0";
    [PassValueClass sharedIntance].typeStr      = @"0";
}


#pragma mark - ResignKeyboard - 重置键盘焦点

- (IBAction)hideddressView
{
    _addressListView.hidden = YES;
}

- (IBAction)resignKeyboard
{
    [_startPlace resignFirstResponder];
    [_endPlace   resignFirstResponder];
}

#pragma mark - TextViewDelegate - TextView代理

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
}

#pragma mark - CreateVoiceWidget - 打开语音输入

- (IBAction)createVoiceWidget
{
    if (!_ttsWidget)
    {
        _ttsWidget = [[TTSWidget alloc] init];
    }
    
    _ttsWidget.delegate = self;
    [_ttsWidget createRecognizerWidget];
    [self addSubview:_ttsWidget];
    _ttsWidget.frame = kRecongnizerRect;
    [_ttsWidget startRecongnize];
}


#pragma mark - AddressView - 地址簿相关函数

- (IBAction)openAddressView//打开地址簿
{
    _addressListView.hidden = NO;

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults]objectForKey:kMyAddressBook]];
    NSArray      *array       = [dict objectForKey:kAddressBookArray];
    
    _dataArray = [NSMutableArray arrayWithArray:array];

    [_addressTBView reloadData];
}

- (IBAction)addThisAddress//加入地址簿
{
    if (!isAddThisAddress)
    {
        isAddThisAddress = YES;
        [_addThisAddressBtn setImage:[UIImage imageNamed:@"checkbox_on.png"] forState:UIControlStateNormal];
    }
    else
    {
        isAddThisAddress = NO;
        [_addThisAddressBtn setImage:[UIImage imageNamed:@"checkbox_off.png"] forState:UIControlStateNormal];
    }
}

#pragma mark - RequestTaxi - 开始请求,进入poi搜索结果

- (IBAction)requestTaxi
{
    //如果没有输入地址
    if (_endPlace.text == nil)
    {
        UIAlertView *noAddressAlert = [[UIAlertView alloc] initWithTitle:@"请您先输入要去的地方" message:nil delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:nil, nil];
        [noAddressAlert show];
    }
    else
    {
        NSString *cityStr = [PassValueClass sharedIntance].cityStr;
        NSString *keyStr  = [NSString stringWithFormat:@"%@",_endPlace.text];
        _POISearcher.delegate = self;
        [_POISearcher poiSearchInCity:cityStr withKey:keyStr pageIndex:0];//开始搜索poi地址
        [MBProgressHUD showHUDAddedTo:self animated:YES];
    }
}

- (void)onGetPoiResult:(NSArray *)poiResultList searchType:(int)type errorCode:(int)error
{
    [MBProgressHUD hideHUDForView:self animated:YES];
    if (error == BMKErrorOk)
    {
       _resultpoi = [poiResultList objectAtIndex:0];
        if (_resultpoi.poiInfoList.count > 0)//如果有数据返回
        {
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kIsFromAddressListView];//正常情况,确认地址试图
            _addressResultView.hidden = NO;
            
            _addressResultView.resultpoi = _resultpoi;
            [_addressResultView.addressResultTBView reloadData];
        }
        else
        {
            UIAlertView *noAddressAlert=[[UIAlertView alloc] initWithTitle:@"出错"
                                                                   message:@"地图目前没有您选择的目的地"
                                                                  delegate:self
                                                         cancelButtonTitle:@"好的"
                                                         otherButtonTitles:nil];
            [noAddressAlert show];
        }
    }
    else
    {
        UIAlertView *noAddressAlert=[[UIAlertView alloc] initWithTitle:@"出错"
                                                               message:@"地图目前没有您选择的目的地"
                                                              delegate:self
                                                     cancelButtonTitle:@"好的"
                                                     otherButtonTitles:nil];
        [noAddressAlert show];
    }
}


#pragma mark - TextField Delegate - TextField 代理

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([string isEqualToString:@"\n"])
    {
        [_endPlace resignFirstResponder];
        return NO;
    }
    return YES;
}

- (void)getAddress1
{
    _endPlace.text = [PassValueClass sharedIntance].voiceStr;
}

#pragma mark -TBView Delegate - TBView 代理

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [_dataArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *tableIdentifier = @"SimpleTableIdentifier";
	UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:tableIdentifier];
	if (cell==nil)
    {
		cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:tableIdentifier];
	}
    
    NSDictionary *dict = [_dataArray objectAtIndex:indexPath.row];
//    NSLog(@"%@",dict);
    NSString *nameStr  = [dict objectForKey:kAddressName];
    NSString *poiStr   = [dict objectForKey:kPoiName];
    
    cell.textLabel.text = [NSString stringWithFormat:@"%@--%@",nameStr,poiStr];
	return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath//选择一个地址
{
    NSDictionary *dict = [_dataArray objectAtIndex:indexPath.row];
    NSString *poiStr   = [dict objectForKey:kPoiName];
    _endPlace.text = poiStr;
    
    _addressListView.hidden = YES;
}

#pragma mark - DaCheDou - 打车豆相关

- (IBAction)openBuyCoinsView
{
    ZhiFuView *zhifuView = [[ZhiFuView alloc] init];
    [self addSubview:zhifuView];
}

- (IBAction)addCoins
{
    if ([_daCheDouLbl.text intValue] < 50)
    {
        return;
    }
    
    if ([_daCheDouLbl.text intValue] >= 50)
    {
        _daCheDouLbl.text     = [NSString stringWithFormat:@"%d",[_daCheDouLbl.text intValue]     - 50];
        _costDaCheDouLbl.text = [NSString stringWithFormat:@"%d",[_costDaCheDouLbl.text intValue] + 50];
        
        if ([_costDaCheDouLbl.text intValue] >= 50)
        {
            [PassValueClass sharedIntance].costDaCheDou = [NSString stringWithFormat:@"%@",_costDaCheDouLbl.text];
            [PassValueClass sharedIntance].typeStr = @"1";
        }
    }
}

- (IBAction)minusCoins
{
    if ([_costDaCheDouLbl.text intValue] < 50)
    {
        return;
    }
    
    if ([_costDaCheDouLbl.text intValue] >= 50)
    {
        _daCheDouLbl.text     = [NSString stringWithFormat:@"%d",[_daCheDouLbl.text intValue]     + 50];
        _costDaCheDouLbl.text = [NSString stringWithFormat:@"%d",[_costDaCheDouLbl.text intValue] - 50];
    
        if ([_costDaCheDouLbl.text intValue] == 0)
        {
            [PassValueClass sharedIntance].costDaCheDou = [NSString stringWithFormat:@"%@",_costDaCheDouLbl.text];
            [PassValueClass sharedIntance].typeStr = @"0";
        }
    }
}

@end
